

/**
 * // 存储,可设置过期时间
 * @param {string} key 存储的key
 * @param {string} value 存储的 value
 * @param {number} expires 存储的 小时数
 * @returns undefined
 */
export const setLocalStorage = (key:string, value:any, expires?: number) => {
  const params = { key, value, expires }
  if (expires) {
    // 记录何时将值存入缓存，毫秒级
    var data = Object.assign(params, { startTime: new Date().getTime() })
    localStorage.setItem(key, JSON.stringify(data))
  } else {
    if (Object.prototype.toString.call(value) == '[object Object]') {
      value = JSON.stringify(value)
    }
    if (Object.prototype.toString.call(value) == '[object Array]') {
      value = JSON.stringify(value)
    }
    localStorage.setItem(key, value)
  }
}

/**
 * // 取出
 * @param {string} key  取值用到的 key
 * @returns string 从storage里面取出 对应的缓存值 
 */
export const getLocalStorage = (key) => {
  let item = localStorage.getItem(key) || '{}'
  // 先将拿到的试着进行json转为对象的形式
  try {
    item = JSON.parse(item)
  } catch (error) {
    // eslint-disable-next-line no-self-assign
    item = item
  }
  // 如果有startTime的值，说明设置了失效时间
  if (item && item.startTime) {
    const date = new Date().getTime()
    // 如果大于就是过期了，如果小于或等于就还没过期
    if (date - item.startTime > (item.expires * 3600000)) {
      localStorage.removeItem(key)
      return false
    } else {
      return item.value
    }
  } else {
    return item
  }
}

/**
 * 获取当前设备的 OS类型 ，和 版本 
 * @returns {Platform, OsVersion } Object
 */
export const getSystemInfo =  () => {
  let ua = navigator.userAgent,
      Platform = 'Unknown', 
      OsVersion = 'Unknown';

  // device & system
  let ipod = ua.match(/(ipod).*\s([\d_]+)/i),
    ipad = ua.match(/(ipad).*\s([\d_]+)/i),
    iphone = ua.match(/(iphone)\sos\s([\d_]+)/i),
    android = ua.match(/(android)\s([\d\.]+)/i);
  
  if (android) {
    Platform = 'Android'
    OsVersion = android[2];
  } else if (iphone) {
    Platform = 'iPhone'
    OsVersion = iphone[2].replace(/_/g,'.');
  } else if (ipad) {
    Platform = 'iPad'
    OsVersion =  ipad[2].replace(/_/g, '.');
  } else if (ipod) {
    Platform = 'ipod'
    OsVersion =   ipod[2].replace(/_/g, '.');
  }

  return {
    Platform,
    OsVersion
  }
}

/**
 * 
 * @param {string} str 需要被解析的目标字符串 
 * @param {string} name 
 * @returns 
 */
export const queryQueryString = (str = '', name: string) => {
  if(!name) return ''
  const _str = str || location.href
  const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
  const _val = _str.split('?')[1]?.match(reg)
  if(_val != null) {
    return _val[2]
  }
  return ''
}
